﻿using System;
using System.Drawing;
using System.Windows.Forms;

public class WatermarkedTextBox : TextBox
{
    private string watermarkText;
    private Color watermarkColor = Color.LightGray;

    public WatermarkedTextBox()
    {
        this.ForeColor = watermarkColor;
        this.Text = watermarkText;
        this.GotFocus += WatermarkedTextBox_GotFocus;
        this.LostFocus += WatermarkedTextBox_LostFocus;
    }

    // 公有属性以允许外部修改水印文本和颜色
    public string WatermarkText
    {
        get { return watermarkText; }
        set { watermarkText = value; UpdateWatermark(); }
    }

    public Color WatermarkColor
    {
        get { return watermarkColor; }
        set { watermarkColor = value; UpdateWatermark(); }
    }

    private void WatermarkedTextBox_GotFocus(object sender, EventArgs e)
    {
        if (this.Text == watermarkText)
        {
            this.Text = "";
            this.ForeColor = Color.Black;
        }
    }

    private void WatermarkedTextBox_LostFocus(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(this.Text))
        {
            this.Text = watermarkText;
            this.ForeColor = watermarkColor;
        }
    }

    private void UpdateWatermark()
    {
        if (string.IsNullOrWhiteSpace(this.Text))
        {
            this.Text = watermarkText;
            this.ForeColor = watermarkColor;
        }
    }
}
